<script setup lang='ts'>
import { computed, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getDelteacher, getLabel, getTeach, getAddteacher, getAllteach, getChangeteach } from '@/api/interface/http1';
import { ElMessageBox } from 'element-plus';
import type { UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { resetForm } from '@/utils/ruoyi';
import { getToken } from '@/utils/auth';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';

interface RuleForm {
    name: string;
    user: string;
    office: string;
    label: [];
    excel: string;
    Introduction: string;
    address: string;
    type: string[];
    resource: string;
    desc: string;
}

const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    name: '',
    user: '',
    office: '',
    label: [],
    excel: '',
    Introduction: '',
    address: '',
    type: [],
    resource: '',
    desc: ''
});
// 校验
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入', trigger: 'blur' },
        { min: 1, max: 11, message: '请输入1', trigger: 'blur' }
    ],
    user: [
        {
            required: true,
            message: '请选择用户',
            trigger: 'blur'
        }
    ],
    office: [
        {
            required: true,
            message: '请输入咨询师办公电话',
            trigger: 'blur'
        },
        { pattern: /^0\d{2,3}-\d{7,8}$/, message: '请输入合法电话号', trigger: 'blur' }
    ],
    label: [
        {
            required: true,
            message: '请选择标签',
            trigger: 'blur'
        }
    ],
    excel: [
        {
            required: true,
            message: '请输入擅长内容',
            trigger: 'blur'
        }
    ],
    Introduction: [
        {
            required: true,
            message: '请输入简介信息',
            trigger: 'blur'
        }
    ],
    address: [
        {
            required: true,
            message: '请输入地址',
            trigger: 'blur'
        }
    ]
});

const picture = ref();
const excelteach = ref('');
;
const teachIntroduction = ref('');
const addressteach = ref('');
const num = ref(0);
const num1 = ref();
const input = ref('');
const input1 = ref('');
;
const officeteach = ref('');
const userteach = ref();
const labelteach = ref([]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const avatarUploadUrl = baseUrl + '/common/upload';
const headers = ref({
    'Authorization': 'Bearer ' + getToken()
});
const props = {
    expandTrigger: 'hover' as const
};
const dialogFormVisible = ref(false);
// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return tableData.value.slice(start, end);
});

const handleCurrentChange = (newPage: number) => {
    currentPage.value = newPage;
};

const handleSizeChange = (newSize: number) => {
    pageSize.value = newSize;
};
let params = reactive({
    name: '',
    mobile: '',
    pageSize: 100,
    pageNum: 1
});
// 请求
const tableData = ref([]);
const options = ref([]);
const option = ref([]);

function getTeachlist() {
    getTeach(params).then(res => {
        // console.log(res);
        tableData.value = res.rows;
        totalItems.value = res.total;
    });
}

getTeachlist();

// 获取标签
getLabel(params).then(res => {
    // console.log(res.rows);
    option.value = res.rows.map(item => {
        return {
            label: item.label,
            value: item.id
        };
    });
});
const dialogVisible = ref(false);
// 删除
const open = (row: any) => {
    ElMessageBox.confirm(
        '此操作将永久删除该文件，是否继续?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    )
        .then(() => {
            let params = row.id;
            getDelteacher(params).then(res => {
                console.log(res);
                getTeachlist();
            });
            ElMessage({
                type: 'success',
                message: '已成功删除'
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            });
        });
};
// 搜索
let Search = () => {
    params.name = input.value;
    params.mobile = input1.value;
    getTeachlist();
};
// 重置
let reset = () => {
    input.value = '';
    input1.value = '';
    Search();
};

// 添加
let data = reactive({
    id: '',
    name: '',
    mobile: '',
    avatar: '',
    gender: '',
    profession: '',
    infos: '',
    status: '',
    location: '',
    labels: [
        ''
    ],
    phone: '',
    userId: '',
    weight: 0
});
getAllteach(data).then(res => {
    // console.log(res.rows);
    options.value = res.rows.map(item => {
        return {
            value: item.userId,
            label: item.name
        };
    });
});
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // console.log('submit!');
            dialogFormVisible.value = false;
            // data.name = value.value;
            data.infos = ruleForm.Introduction;
            data.location = ruleForm.address;
            data.phone = ruleForm.office;
            data.profession = ruleForm.excel;
            data.weight = num.value;
            // data.labels = value1.value;
            getAddteacher(data).then(res => {
                if (res.code === 200) {
                    ElMessage({
                        type: 'success',
                        message: '成功添加咨询师！'
                    });
                    getTeachlist();
                    tableData.value.push(data);
                }
            });
            ruleForm.user = '';
            ruleForm.Introduction = '';
            ruleForm.address = '';
            ruleForm.office = '';
            ruleForm.excel = '';
            num.value = 0;
            ruleForm.label = [];
            imageUrl.value = '';
            picture.value = '';
        } else {
            // console.log('error submit!', fields);
        }
    });
};

const imageUrl = ref('');

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    data.avatar = response.url;
    // console.log(response);
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!');
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!');
        return false;
    }
    return true;
};

//编辑
const Changeteach = (index: number, row: any) => {
    dialogVisible.value = true;
    data.id = tableData.value[index].id;
    data.avatar = row.avatar;
    // console.log(row);
    userteach.value = row.name;
    teachIntroduction.value = row.infos;
    addressteach.value = row.location;
    officeteach.value = row.phone;
    excelteach.value = row.profession;
    num1.value = row.weight;
    labelteach.value = row.labels.map(item => {
        return item.label;
    });
    // imageUrl.value = row.avatar;
};
const Savechange = () => {
    dialogVisible.value = false;
    // data.avatar = imageUrl.value;
    data.infos = teachIntroduction.value;
    data.location = addressteach.value;
    data.phone = officeteach.value;
    data.profession = excelteach.value;
    data.status = '0';
    data.weight = num1.value;
    data.name = userteach.value;
    getChangeteach(data).then(res => {
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '咨询师编辑成功！'
            });
            getTeachlist();
        }
    });
};

function change(e) {
    // console.log(e);
    data.userId = e.value;
    data.name = e.label;
}

function changeLabel(e) {

    data.labels = e.map(item => {
        return item.label;
    });
    // console.log(data.labels);
}
</script>

<template>
    <div>
        <div class='boxTop'>
            <div>
                <label for=''>姓名</label>
                <el-input
                    v-model='input'
                    style='width: 190px;height: 36px'
                    placeholder='请输入姓名'
                    clearable
                    @input="Search"
                />
            </div>
            <div>
                <label for=''>电话</label>
                <el-input
                    v-model='input1'
                    @input="Search"
                    style='width: 190px;height: 36px'
                    placeholder='请输入电话'
                    clearable
                />
            </div>
            <div>
                <el-button style='width: 70px;height: 36px' @click='reset'>重置</el-button>
                <el-button type='primary' style='width: 70px;height: 36px' @click='Search'>搜索</el-button>
            </div>
        </div>
        <!--        添加-->
        <div class='addTo'>
            <!--            <el-button plain @click="dialogFormVisible = true">-->
            <el-button type='primary' @click='dialogFormVisible = true'>
                <span>添加</span>
            </el-button>

            <el-dialog v-model='dialogFormVisible' title='添加' width='700'>
                <el-form
                    ref='ruleFormRef'
                    style='max-width: 600px'
                    :model='ruleForm'
                    :rules='rules'
                    label-width='auto'
                    class='demo-ruleForm'
                    :size='formSize'
                    status-icon
                    :hide-required-asterisk='true'
                >
                    <!--                    <el-form-item label='' prop='region'>-->
                    <label for='' style='margin-top: -160px'>头像</label>
                    <el-upload
                        v-model='picture'
                        class='avatar-uploader'
                        :action='avatarUploadUrl'
                        :show-file-list='false'
                        :on-success='handleAvatarSuccess'
                        :before-upload='beforeAvatarUpload'
                        :headers='headers'
                    >
                        <img v-if='imageUrl' :src='imageUrl' class='avatar' />
                        <el-icon style='' v-else class='avatar-uploader-icon'>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <!--                    </el-form-item>-->
                    <el-form-item label='选择用户' prop='user'>
                        <div class='frame'>
                            <el-select
                                v-model='ruleForm.user'
                                placeholder='用户姓名'
                                size='large'
                                style='width: 275px;margin-left: 40px;'
                                @change='change'
                            >
                                <el-option
                                    v-for='item in options'
                                    :key='item.value'
                                    :label='item.label'
                                    :value='item'
                                />
                            </el-select>
                        </div>
                    </el-form-item>
                    <div class='frame' style='margin-bottom: 20px'>
                        <label for=''>权重</label>
                        <el-space>
                            <el-input-number v-model='num' controls-position='right'
                                             style='margin-left: 80px;width: 275px' />
                        </el-space>
                    </div>
                    <el-form-item label='办公电话' prop='office'>
                        <div class='frame'>
                            <el-input v-model='ruleForm.office' style='width: 550px;margin-left: 40px'
                                      placeholder='请输入咨询师办公电话' />
                        </div>
                    </el-form-item>
                    <el-form-item label='标签设置' prop='label'>
                        <div class='frame'>
                            <el-select
                                v-model='ruleForm.label'
                                placeholder='选择标签'
                                multiple
                                size='large'
                                style='width: 550px;margin-left: 40px;'
                                @change='changeLabel'
                            >
                                <el-option
                                    v-for='item in option'
                                    :key='item.value'
                                    :label='item.label'
                                    :value='item'
                                />
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label='专业擅长' prop='excel'>
                        <div class='frame'>
                            <el-input
                                v-model='ruleForm.excel'
                                style='width: 550px;margin-left: 40px;height: 95px'
                                maxlength='500'
                                placeholder='请输入擅长内容'
                                show-word-limit
                                type='text'
                            />
                        </div>
                    </el-form-item>
                    <el-form-item label='老师简介' prop='Introduction'>
                        <div class='frame'>
                            <el-input
                                v-model='ruleForm.Introduction'
                                style='width: 550px;margin-left: 40px;height: 95px'
                                maxlength='500'
                                placeholder='请输入简介信息'
                                show-word-limit
                                type='text'
                            />
                        </div>
                    </el-form-item>
                    <el-form-item label='办公地址' prop='address'>
                        <div class='frame'>
                            <el-input
                                v-model='ruleForm.address'
                                style='width: 550px;margin-left: 40px;'
                                maxlength='50'
                                placeholder='请输入办公地址'
                                show-word-limit
                                type='text'
                            />
                        </div>
                    </el-form-item>
                    <el-form-item style='margin-left: 445px '>
                        <el-button @click='dialogFormVisible = false'>取消</el-button>
                        <el-button type='primary' @click='submitForm(ruleFormRef)'>
                            保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <div class='section'>
            <el-table :data='paginatedData' border style='width: 100%;'>
                <el-table-column type='index' width='115' label='序号' />
                <el-table-column prop='name' label='用户名称' />
                <el-table-column prop='mobile' label='联系电话' />
                <el-table-column prop='phone' label='办公电话' />
                <el-table-column prop='location' label='地址' width='350' />
                <el-table-column prop='createTime' label='创建时间' />
                <el-table-column label='操作'>
                    <template #default='scope'>
                        <el-button plain @click='Changeteach(scope.$index,scope.row)'
                                   style='background-color: transparent;border: none;color: #409EFF'>
                            <span>编辑</span>
                        </el-button>
                        <el-button plain @click='open(scope.row)' style='background-color: transparent;border: none;color: #409EFF'>删除</el-button>

                    </template>
                </el-table-column>
            </el-table>
            <el-dialog v-model='dialogVisible' title='编辑' width='700'>
                <!--                                头像-->
                <label for='' style='vertical-align: top'>头像</label>
                <el-upload
                    class='avatar-uploader'
                    :action='avatarUploadUrl'
                    :show-file-list='false'
                    :headers='headers'
                    :on-success='handleAvatarSuccess'
                    :before-upload='beforeAvatarUpload'
                >
                    <img v-if='data.avatar' :src='baseUrl+data.avatar' class='avatar' />
                    <el-icon style='' v-else class='avatar-uploader-icon'>
                        <Plus />
                    </el-icon>
                </el-upload>
                <!--                选择用户-->
                <div class='frame'>
                    <label for=''>咨询师</label>
                    <el-input
                        v-model='userteach'
                        style='width: 240px;margin-left: 65px'
                        disabled
                        placeholder=''
                    />
                </div>
                <!--                权重-->
                <div class='frame'>
                    <label for=''>权重</label>
                    <el-space>
                        <el-input-number v-model='num1' controls-position='right'
                                         style='margin-left: 78px;width: 275px' />
                    </el-space>
                </div>
                <!--                办公电话-->
                <div class='frame'>
                    <label for=''>办公电话</label>
                    <el-input v-model='officeteach' style='width: 550px;margin-left: 50px'
                              placeholder='请输入咨询师办公电话' />
                </div>
                <div class='frame'>
                    <label for=''>标签设置</label>
                    <el-select
                        v-model='labelteach'
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        :reserve-keyword='false'
                        placeholder='选择标签'
                        size='large'
                        style='width: 550px;margin-left: 50px;'
                    >
                        <el-option
                            v-for='item in option'
                            :key='item.value'
                            :label='item.label'
                            :value='item.value'
                        />
                    </el-select>
                </div>
                <div class='frame'>
                    <label for='' style='vertical-align: top'> 专业擅长</label>
                    <el-input
                        v-model='excelteach'
                        style='width: 550px;margin-left: 50px;height: 95px'
                        maxlength='500'
                        placeholder='请输入擅长内容'
                        show-word-limit
                        type='text'
                    />
                </div>
                <div class='frame'>
                    <label for='' style='vertical-align: top'> 老师简介</label>
                    <el-input
                        v-model='teachIntroduction'
                        style='width: 550px;margin-left: 50px;height: 95px'
                        maxlength='500'
                        placeholder='请输入简介信息'
                        show-word-limit
                        type='text'
                    />
                </div>
                <div class='frame'>
                    <label for='' style='vertical-align: top'>办公地址</label>
                    <el-input
                        v-model='addressteach'
                        style='width: 550px;margin-left: 50px;'
                        maxlength='50'
                        placeholder='请输入办公地址'
                        show-word-limit
                        type='text'
                    />
                </div>
                <template #footer>
                    <div class='dialog-footer'>
                        <el-button @click='dialogVisible = false'>取消</el-button>
                        <el-button type='primary' @click='Savechange'>
                            保存
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
        <div class='footer'>
            <el-pagination background @sizeChange='handleSizeChange' @currentChange='handleCurrentChange'
                           :current-page='currentPage' :page-sizes='[10, 20, 30, 40]' :page-size='pageSize'
                           :total='totalItems'>
            </el-pagination>
        </div>
    </div>
</template>

<style scoped lang='less'>
.boxTop {
    box-sizing: border-box;
    //width: 1138px;
    height: 60px;
    //padding-left: 18px;
    margin-top: 40px;

    > div {
        float: left;
        margin-left: 48px;

        label {
            color: #606266;
            font-size: 14px;
            font-weight: 700;
            margin-right: 10px;
        }
    }
}

.addTo {
    margin-left: 32px;
    margin-bottom: 20px;
    button {
        width: 70px;
        height: 36px;
    }

    :deep(.el-dialog__header) {
        text-align: left;
        width: 700px;
        background-color: rgb(24, 146, 255);

        .el-dialog__title {
            color: white;
        }

        svg {
            color: white;
        }
    }

}
:deep(.el-input__inner){
    text-align: left;
}
.section {
    padding: 0px 30px;
    margin-top: 10px;
    margin-bottom: 50px;
    width: auto;

    :deep(.el-dialog__header) {
        text-align: left;
        width: 700px;
        background-color: rgb(24, 146, 255);

        .el-dialog__title {
            color: white;
        }

        svg {
            color: white;
        }
    }

    :deep(.el-table__row) {
        height: 67px !important;

        td {
            text-align: center;
            padding: 0;

            button {
                width: 25px;
                height: 31px;
                font-size: 12px;
            }
        }
    }

    :deep(.cell) {
        //height: 50px;
        line-height: 20px;
        text-align: center;
    }

    //.contentTree {
    //    margin: auto;
    //    margin-top: 30px;
    //    width: 700px;
    //    background-color: #eeeeee;
    //    text-align: left;
    //}
}


.footer {
    float: right;
    margin-bottom: 80px;
    margin-right: 50px;
}

//添加
.frame {
    margin-bottom: 5px;

}

:deep(.el-form-item__error) {
    left: 40px;
}

.avatar-uploader {
    display: inline-block;
    margin-left: 80px;
    margin-bottom: 20px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader-icon {
    border: 1px dashed #cccccc;
    border-radius: 7px;
}
</style>
